package com.collegeproject.weatherapp.fragments;

import java.util.HashMap;

import org.apache.http.entity.StringEntity;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.collegeproject.weatherapp.R;
import com.collegeproject.weatherapp.StartActivity.FragmentListener;
import com.collegeproject.weatherapp.library.AsyncResponse;
import com.collegeproject.weatherapp.library.ConnectionDetector;
import com.collegeproject.weatherapp.library.DatabaseHandler;
import com.collegeproject.weatherapp.library.HTTPfunctions;

public class EditFragment extends Fragment implements AsyncResponse {
	Button btnEdit, btnBack;
	TextView username, error;
	EditText inputCurrentPass, inputNewPass, inputFirst, inputLast, inputEmail;
	
	static FragmentListener _listener;
	
	ConnectionDetector cd;

	private String CurrentPassword, CurrentUserName, CurrentEmail, CurrentFirst,
			CurrentLast, passwordToSave;
	private String sCurrentPass, sNewPass, sEmail, sFirstName, sLastName;

	// private static String localEditURl = "http://10.0.2.2:8080/WeatherAppService.svc/rest/edit";
	private static String editURL = "http://x00068868.cloudapp.net/WeatherAppService/rest/edit";

	private static final String TAG = "EditFragment";
	private static final String POSTAUTH = "POSTAUTH";

	private static final String KEY_USERNAME = "UserName";
	private static final String KEY_USERID = "UserId";
	private static final String KEY_FIRSTNAME = "FirstName";
	private static final String KEY_LASTNAME = "LastName";
	private static final String KEY_EMAIL = "Email";

	public static EditFragment newInstance(FragmentListener listener) {
		EditFragment f = new EditFragment();
		_listener = listener;
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.editdetails, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initViews();
		cd = new ConnectionDetector(getActivity());
	}

	@Override
	public void onStart() {
		super.onStart();

		// get current user details
		DatabaseHandler db = new DatabaseHandler(getActivity());
		HashMap<String, String> user = new HashMap<String, String>(
				db.getUserDetails());

		CurrentPassword = user.get("password");
		CurrentUserName = user.get("username");
		CurrentEmail = user.get("email");
		CurrentFirst = user.get("firstname");
		CurrentLast = user.get("lastname");

		// display the user detail in view
		username.setText("Username: " + CurrentUserName);
		username.setBackgroundColor(Color.GRAY);
		username.setVisibility(View.VISIBLE);

		inputFirst.setText(CurrentFirst);
		inputLast.setText(CurrentLast);
		inputEmail.setText(CurrentEmail);
		
		inputEmail.setOnEditorActionListener(new OnEditorActionListener() {

			@SuppressWarnings("static-access")
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {

				// search button pressed
				if (actionId == EditorInfo.IME_ACTION_SEND) {
					
					sEmail = inputEmail.getText().toString().trim();
					// sCurrentPass = inputCurrentPass.getText().toString();
					sNewPass = inputNewPass.getText().toString().trim();
					sFirstName = inputFirst.getText().toString().trim();
					sLastName = inputLast.getText().toString().trim();
					
					attemptEdit(sCurrentPass, sNewPass, sEmail, sFirstName,
							sLastName, CurrentPassword, CurrentUserName);
					
					// hide the keyboard
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									getActivity().INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
					
					return true;
				}
				return false;
			}
		});
		
		btnEdit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sEmail = inputEmail.getText().toString().trim();
				// sCurrentPass = inputCurrentPass.getText().toString();
				sNewPass = inputNewPass.getText().toString().trim();
				sFirstName = inputFirst.getText().toString().trim();
				sLastName = inputLast.getText().toString().trim();
				attemptEdit(sCurrentPass, sNewPass, sEmail, sFirstName,
						sLastName, CurrentPassword, CurrentUserName);
			}
		});

		btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// switch back to dash board
				_listener.onSwitchToNextFragment();
			}
		});
	}

	private void initViews() {
		btnEdit = (Button) getView().findViewById(R.id.button_edit);
		btnBack = (Button) getView().findViewById(R.id.button_edit_back);

		error = (TextView) getView().findViewById(R.id.edit_error);
		username = (TextView) getView().findViewById(R.id.textViewEditUsername);

		/*
		 * inputCurrentPass = (EditText) getView().findViewById(
		 * R.id.editTextEditPass3);
		 */
		inputNewPass = (EditText) getView()
				.findViewById(R.id.editTextEditPass4);
		inputEmail = (EditText) getView().findViewById(R.id.editTextEditEmail);
		inputFirst = (EditText) getView().findViewById(
				R.id.editTextEditFirstName);
		inputLast = (EditText) getView()
				.findViewById(R.id.editTextEditLastName);
	}

	private void attemptEdit(String sCurrentPass, String sNewPass,
			String sEmail, String sFirstName, String sLastName,
			String currentPassword, String currentUsername) {

		// inputCurrentPass.setError(null);
		inputNewPass.setError(null);
		inputFirst.setError(null);
		inputLast.setError(null);
		inputEmail.setError(null);

		boolean cancel = false;
		View focusView = null;

		/*
		 * if (TextUtils.isEmpty(sCurrentPass)) {
		 * inputCurrentPass.setError(getString(R.string.error_field_required));
		 * focusView = inputCurrentPass; cancel = true; } else if (sCurrentPass
		 * != currentPassword) { inputCurrentPass
		 * .setError(getString(R.string.error_field_wrongpassword)); focusView =
		 * inputCurrentPass; cancel = true; }
		 */

		// new pass is empty set it as current pass
		if (TextUtils.isEmpty(sNewPass)) {
			sNewPass = currentPassword;

			// valid pass check
		} else if (sNewPass.length() < 6) {
			inputNewPass.setError(getString(R.string.error_field_lesschar));
			focusView = inputNewPass;
			cancel = true;
		}

		// valid email check
		if (!sEmail.contains("@")) {
			inputEmail.setError(getString(R.string.error_invalid_email));
			focusView = inputEmail;
			cancel = true;
		}

		// valid first name check
		if (TextUtils.isEmpty(sFirstName)) {
			inputFirst.setError(getString(R.string.error_field_required));
			focusView = inputFirst;
			cancel = true;
		}

		// valid last name check
		if (TextUtils.isEmpty(sLastName)) {
			inputLast.setError(getString(R.string.error_field_required));
			focusView = inputLast;
			cancel = true;
		}

		if (cancel) {
			focusView.requestFocus();
		} else {
			try {
				Boolean connected = cd.isConnectingToInternet();
				if (connected){
					passwordToSave = sNewPass;

					String source = currentUsername + ":" + currentPassword;
					String base64 = Base64.encodeToString(
							source.getBytes("UTF-8"), Base64.URL_SAFE
									| Base64.NO_WRAP);

					JSONObject editUser = new JSONObject();
					editUser.put("Password", sNewPass);
					editUser.put("Email", sEmail);
					editUser.put("FirstName", sFirstName);
					editUser.put("LastName", sLastName);					

					StringEntity se = new StringEntity(editUser.toString());

					HTTPfunctions task = new HTTPfunctions(getActivity(),
							POSTAUTH, se, base64);
					task.listener = this;
					task.execute(new String[] { editURL });
				} else {
					error.setText("No internet connection available");
					error.setVisibility(View.VISIBLE);
				}
			} catch (Exception ex) {
				Log.e(TAG, "Attempt Edit " + ex.getMessage());
			}
		}
	}

	@Override
	public void processFinish(String result) {
		try {
			JSONObject jsonObject = new JSONObject(result);
			int success = Integer.parseInt(jsonObject.getString("Success"));
			if (success == 0) { // success
				// show confirmation to user
				Toast.makeText(getActivity(), "Updated User Details",
						Toast.LENGTH_LONG).show();

				// save the new user details in the database table
				JSONObject user = jsonObject.getJSONObject("User");
				logoutUser(getActivity());
				DatabaseHandler db = new DatabaseHandler(getActivity());
				db.addUser(user.getString(KEY_USERNAME),
						user.getString(KEY_EMAIL), user.getString(KEY_USERID),
						user.getString(KEY_FIRSTNAME),
						user.getString(KEY_LASTNAME), passwordToSave);

				// switch to dash board
				_listener.onSwitchToNextFragment();
			} else if (success == 3) {
				error.setText("Server rejected the request send");
				error.setVisibility(View.VISIBLE); // error
			} else {
				error.setText(jsonObject.getString("ErrorMessage"));
				error.setVisibility(View.VISIBLE); // error
			}
		} catch (Exception e) {
			Log.e(TAG, "Post Result " + e.getMessage());
		}
	}

	public void logoutUser(Context context) {
		DatabaseHandler db = new DatabaseHandler(context);
		db.resetTables();
	}
}